/**
 * Created by wry on 2015/1/13.
 */


var Activity = mongoose.model('activity');
var ActivityChats = mongoose.model('activity_chats');
var Relation = mongoose.model('Relation_userAcitvity');
var toolUtil = require('../common/utils/toolUtil');
var cacheUtil = require('../common/utils/cacheUtil');
var UserFollowups = mongoose.model('user_followups');
var Users = mongoose.model('user');
var async = require('async');
var moment = require('moment');
var neighbourActivity = mongoose.model('activity_neighbour');
var Dic = mongoose.model('masterData_Dictionaries');
var SystemMessage = mongoose.model('system_messages');
var ugcIndex = mongoose.model('system_ugcIndex');
var QuestionReplyPraise = mongoose.model('question_replypraises');
var QuestionReport = mongoose.model('question_reports');
var ugcReply = mongoose.model('system_ugcReply');
var QuestionReplyThank = mongoose.model('question_replythanks');
var replyAt = mongoose.model('question_replyAt');
var PartakeInfo = mongoose.model('activity_partake_info');

/**
 * 创建活动
 */
exports.createActivityService = function (input, token, callback) {

    toolUtil.getUserByToken(token, function (err, user) {
        if (user == null) {
            var msg = {
                "message": noUserErrMessage
            };
            callback(msg, null);
        } else {
            toolUtil.getAndCacheHuanXinToken(function (err, token) {
                var args = {
                    data: {
                        "groupname": input.activityName, //群组名称, 此属性为必须的
                        "desc": input.activityDesc, //群组描述, 此属性为必须的
                        "public": true, //是否是公开群, 此属性为必须的
                        "maxusers": 200, //群组成员最大数(包括群主), 值为数值类型,默认值200,此属性为可选的
                        "approval": false, //加入公开群是否需要批准, 没有这个属性的话默认是true（不需要群主批准，直接加入）, 此属性为可选的
                        "owner": user.huanxinUserName//群组的管理员, 此属性为必须的
                    },
                    headers: {
                        "Content-Type": "application/json",
                        "Authorization": "Bearer " + token
                    }
                };
                restClient.post("https://a1.easemob.com/66xiaoqu/" + huanxinEnv + "/chatgroups", args, function (data, response) {
                    if (response.statusCode == '200') {
                        var temp = new Activity();
                        if (data.data.groupid != null) {
                            temp.chatGroupId = data.data.groupid;
                        }
                        temp.activityCategory = input.activityCategory;
                        temp.activityName = input.activityName;
                        temp.activityVenue = input.activityVenue;
                        temp.startDateTime = input.startDateTime;
                        temp.endDateTime = input.endDateTime;
                        temp.activityDesc = input.activityDesc;
                        temp.broadcastScope = input.broadcastScope;
                        temp.joinWay = input.joinWay;
                        temp.createdBy = user._id;
                        temp.community = user.community._id;

                        temp.save(callback);
                    } else {
                        logger.error(data);
                        var msg = {
                            "message": "create activity failure"
                        };
                        callback(msg, null);
                    }
                }).on('error', function (err) {
                    logger.error('createActivityService' + err.message);
                });
            });
        }
    });
};

exports.updateActivityService = function (activityId, input, callback) {
    if (input.deadline != null) {
        input.deadline = moment(input.deadline).toDate();
    }
    neighbourActivity.update({_id: activityId}, input, callback);
};


/**
 * 设置活动图片
 */
exports.setImagesToActivity = function (activityId, images, callback) {
    Activity.update({_id: activityId}, {$set: {'images': images}}, callback);
};

/**
 * 获取活动列表
 */
exports.getTopActivityListService = function (token, callback) {
    toolUtil.getUserByToken(token, function (err, user) {
        if (user == null) {
            var msg = {
                "message": noUserErrMessage
            };
            callback(msg, null);
        } else {
            async.series([
                function (callbackInner) {
                    Activity.find({
                        'community': user.community._id,
                        'images.isBackgroundImage': true,
                        'endDateTime': {"$gte": new Date()}
                    }, 'images activityName activityVenue startDateTime endDateTime createdBy')
                        .populate('createdBy', '_id nickName images').exec(function (err, results) {
                            sortActivities('flag', user._id, results, function (err, activities) {
                                callbackInner(err, activities);
                            })
                        })
                },
                function (callbackInner) {
                    Activity.find({
                        'community': user.community._id,
                        'images.isBackgroundImage': true,
                        'endDateTime': {"$lt": new Date()}
                    }, 'images activityName activityVenue startDateTime endDateTime createdBy')
                        .populate('createdBy', '_id nickName images').exec(function (err, results) {
                            sortActivities(null, user._id, results, function (err, activities) {
                                callbackInner(err, activities);
                            })
                        })
                }
            ], callback)
        }
    });
};

/**
 * 活动排序
 */
function sortActivities(flag, userId, activities, callback) {
    async.each(activities, function (activity, callbackInner) {
        if (activity.images != null) {
            activity.images.forEach(function (image) {
                if (image.isBackgroundImage) {
                    activity.images = image;
                }
            })
        }
        UserFollowups.count({'activity': activity._id}, function (err, count) {
            activity._doc['followups'] = count;
            if (flag) {
                var dayDiff = moment(activity.startDateTime).diff(moment(), 'days');
                if (dayDiff <= 0) {
                    activity._doc['status'] = '进行中'
                } else if (dayDiff == 1) {
                    activity._doc['status'] = '明天'
                } else if (dayDiff == 2) {
                    activity._doc['status'] = '后天'
                } else if (dayDiff == 3) {
                    activity._doc['status'] = '3天后'
                } else {
                    activity._doc['status'] = '即将开始'
                }
            } else {
                activity._doc['status'] = '已结束'
            }

            var start = moment(activity.startDateTime).format('MM月DD日 HH:mm');
            var end = moment(activity.endDateTime).format('MM月DD日 HH:mm');

            activity._doc['time'] = start + '—' + end;

            activity.startDateTime = undefined;
            activity.endDateTime = undefined;

            UserFollowups.findOne({'user': userId, 'activity': activity._id}, function (err, userFollowup) {
                if (err || userFollowup == null) {
                    activity._doc['isFollowup'] = 'No'
                } else {
                    activity._doc['isFollowup'] = 'Yes'
                }
                callbackInner();
            });
        })
    }, function (err) {
        if (err) {
            callback(err, null);
        } else {
            activities.sort(function (a, b) {
                return b._doc.followups - a._doc.followups;
            });
            callback(null, activities);
        }
    })
}

/**
 * 获取活动详情
 */
exports.getActivityDetailService = function (activityId, token, callback) {
    toolUtil.getUserByToken(token, function (err, user) {
        if (user == null) {
            var msg = {
                "message": noUserErrMessage
            };
            callback(msg, null);
        } else {
            Activity.findOne({_id: activityId}, 'images activityCategory chatGroupId activityName activityVenue startDateTime endDateTime activityDesc broadcastScope joinWay createdBy activityInformation.photos.photoURL activityInformation.photos._id')
                .populate('activityCategory', '_id value').populate('createdBy', '_id nickName images').exec(function (err, result) {
                    if (result != null) {

                        var photos = new Array();
                        if (result.activityInformation != null) {
                            result.activityInformation.forEach(function (info) {
                                photos = photos.concat(info.photos)
                            });
                            result._doc['photos'] = photos;
                            result.activityInformation = undefined;
                        }

                        var start = moment(result.startDateTime).format('MM月DD日 HH:mm');
                        var end = moment(result.endDateTime).format('MM月DD日 HH:mm');

                        result._doc['time'] = start + '—' + end;

                        UserFollowups.findOne({'user': user._id, 'activity': result._id}, function (err, userFollowup) {
                            if (err || userFollowup == null) {
                                result._doc['isFollowup'] = 'No'
                            } else {
                                result._doc['isFollowup'] = 'Yes'
                            }

                            Relation.findOne({'user': user._id, 'activity': result._id}, function (err, res) {
                                if (err || res == null) {
                                    if (user._id == result.createdBy._id) {
                                        result._doc['isRegister'] = 'Yes'
                                    } else {
                                        result._doc['isRegister'] = 'No';
                                    }
                                } else {
                                    result._doc['isRegister'] = 'Yes'
                                }
                            });

                            result._doc['isJoinChat'] = 'No';

                            //获取用户是否已加入聊天室
                            toolUtil.getAndCacheHuanXinToken(function (err, token) {
                                var args = {
                                    headers: {
                                        "Content-Type": "application/json",
                                        "Authorization": "Bearer " + token
                                    }
                                };
                                restClient.get("https://a1.easemob.com/66xiaoqu/" + huanxinEnv + "/users/" + user.huanxinUserName + "/joined_chatgroups", args, function (data, response) {
                                    if (response.statusCode == '200' && data.data != null) {
                                        logger.info(data.data);
                                        data.data.forEach(function (group) {
                                            if (result.chatGroupId == group.groupid) {
                                                result._doc['isJoinChat'] = 'Yes';
                                            }
                                        })
                                    }
                                    callback(err, result);
                                })
                            });

                        });
                    } else {
                        var msg = {
                            "message": "No such activity"
                        };
                        callback(msg, null);
                    }
                })
        }
    });
};

/**
 * 报名活动
 * @param token
 * @param input
 * @param callback
 */
exports.doRegisterService = function (token, input, callback) {
    toolUtil.getUserByToken(token, function (err, user) {
        if (user == null) {
            var msg = {
                "message": noUserErrMessage
            };
            callback(msg, null);
        } else {
            async.waterfall([
                function (callbackInner) {
                    Relation.findOne({'user': user._id, 'activity': input.activityId}, function (err, result) {
                        callbackInner(err, result);
                    })
                },
                function (result, callbackInner) {
                    if (result != null) {
                        var msg = {
                            "message": "The user has been registered"
                        };
                        callbackInner(msg, null);
                    } else {
                        callbackInner(null, 'Yes');
                    }
                },
                function (flag, callbackInner) {
                    if (flag) {
                        Activity.findOne({_id: input.activityId}, 'chatGroupId', function (err, result) {
                            if (result != null) {
                                callbackInner(err, result.chatGroupId);
                            } else {
                                callbackInner(err, null);
                            }
                        })
                    }
                },
                function (groupId, callbackInner) {
                    if (groupId != null) {
                        toolUtil.getAndCacheHuanXinToken(function (err, token) {
                            var args = {
                                data: {},
                                headers: {
                                    "Content-Type": "application/json",
                                    "Authorization": "Bearer " + token
                                }
                            };
                            restClient.post("https://a1.easemob.com/66xiaoqu/" + huanxinEnv + "/chatgroups/" + groupId + "/users/" + user.huanxinUserName, args, function (data, response) {
                                if (response.statusCode == '200') {
                                    var temp = new Relation();
                                    temp.user = user._id;
                                    temp.activity = input.activityId;
                                    temp.contactName = input.contactName;
                                    temp.phone = input.phone;
                                    temp.save(callbackInner);
                                } else {
                                    logger.error(data);
                                    var msg = {
                                        "message": "user joined the chat room failure"
                                    }
                                    callbackInner(msg, null);
                                }

                            }).on('error', function (err) {
                                logger.error('doRegisterService' + err.message);
                                callbackInner(err, null);
                            });
                        });
                    } else {
                        var msg = {
                            "message": "The activity has no chat group"
                        };
                        callbackInner(msg, null);
                    }
                }
            ], callback);
        }
    });
};

/**
 * 发布动态
 */
exports.addActivityInformationService = function (images, input, token, callback) {
    toolUtil.getUserByToken(token, function (err, user) {
        if (user == null) {
            var msg = {
                "message": noUserErrMessage
            };
            callback(msg, null);
        } else {
            var temp = {
                "photos": images,
                "textDesc": input.textDesc,
                "postedBy": user._id
            };
            Activity.update({_id: input.activityId}, {'$push': {'activityInformation': temp}}, callback);
        }
    });
};

exports.getActivityPhotoDetailService = function (activityId, imageId, callback) {
    Activity.findOne({
        _id: activityId
    }, 'activityInformation.postedBy activityInformation.textDesc activityInformation.photos activityInformation.photos.commentsOnPhoto.commentedBy activityInformation.photos.commentsOnPhoto.comments activityInformation.photos.commentsOnPhoto.commnentedDate')
        .populate('activityInformation.postedBy', '_id nickName images').populate('activityInformation.photos.commentsOnPhoto.commentedBy', '_id nickName images')
        .exec(function (err, result) {
            if (result != null && result.activityInformation != null) {
                result.activityInformation.forEach(function (temp) {
                    if (temp.photos != null) {
                        temp.photos.forEach(function (image) {
                            if (image._id.equals(imageId)) {
                                var res = {
                                    "textDesc": temp.textDesc,
                                    "postedBy": temp.postedBy,
                                    "commentsOnPhoto": image.commentsOnPhoto,
                                    "photoURL": image.photoURL
                                }
                                callback(err, res);
                            }
                        })
                    }
                })
            } else {
                callback(null, null);
            }
        })
};

/**
 * 发表图片图片评论
 */
exports.postPhotoCommentService = function (input, token, callback) {
    toolUtil.getUserByToken(token, function (err, user) {
        if (user == null) {
            var msg = {
                "message": noUserErrMessage
            };
            callback(msg, null);
        } else {
            var temp = {
                "comments": input.comments,
                "commentedBy": user._id
            };

            Activity.findOne({_id: input.activityId}, function (err, result) {
                result.activityInformation.forEach(function (info) {
                    if (info.photos != null) {
                        info.photos.forEach(function (image) {
                            if (image._id.equals(input.imageId)) {
                                logger.info(result.activityInformation.id(info._id).photos.id(image._id))
                                result.activityInformation.id(info._id).photos.id(image._id).commentsOnPhoto.push(temp);
                                result.save(callback);
                            }
                        })
                    }
                })
            });
        }
    });
};

/**
 * 获取我的活动列表
 * @param token
 * @param callback
 */
exports.getMyActivityService = function (token, callback) {
    toolUtil.getUserByToken(token, function (err, user) {
        if (user == null) {
            var msg = {
                "message": noUserErrMessage
            };
            callback(msg, null);
        } else {
            async.series([
                function (callbackInner) {
                    Activity.find({'createdBy': user._id}, '_id activityName startDateTime endDateTime createdBy', function (err, results) {
                        if (results != null) {
                            results.forEach(function (result) {
                                result._doc['flag'] = '我发起'
                                result._doc['isFollowup'] = 'No'
                            })
                        }
                        callbackInner(err, results);
                    })
                },
                function (callbackInner) {
                    Relation.find({'user': user._id}, 'activity', function (err, results) {
                        if (results != null) {
                            var ids = new Array();
                            results.forEach(function (res) {
                                ids.push(res.activity);
                            });
                            Activity.find({_id: {$in: ids}}, '_id activityName startDateTime endDateTime createdBy', function (err, results) {
                                if (results != null) {
                                    results.forEach(function (result) {
                                        result._doc['flag'] = '我报名'

                                        UserFollowups.findOne({
                                            'user': user._id,
                                            'activity': result._id
                                        }, function (err, userFollowup) {
                                            if (err || userFollowup == null) {
                                                result._doc['isFollowup'] = 'No'
                                            } else {
                                                result._doc['isFollowup'] = 'Yes';
                                            }
                                        });
                                    })
                                }
                                callbackInner(err, results);
                            })
                        }
                    })
                },
                function (callbackInner) {
                    UserFollowups.find({
                        'user': user._id,
                        'activity': {$ne: null}
                    }, 'activity', function (err, results) {
                        if (results != null) {
                            var ids = new Array(results.length);
                            for (var i = 0; i < results.length; i++) {
                                ids[i] = results[i].activity
                            }
                            Activity.find({_id: {$in: ids}}, '_id activityName startDateTime endDateTime createdBy', function (err, results) {
                                if (results != null) {
                                    results.forEach(function (result) {
                                        result._doc['flag'] = '我关注'
                                        result._doc['isFollowup'] = 'Yes';
                                    })
                                }
                                callbackInner(err, results);
                            })
                        }
                    })
                }
            ], callback)
        }
    });
};

/**
 * 获取活动成员列表
 * @param activityId
 * @param callback
 */
exports.getActivityRegistrationListService = function (activityId, callback) {
    Relation.find({'activity': activityId}, '-_id user contactName phone').populate('user', '_id nickName images').exec(callback)
};

exports.getActivityGroupMemberService = function (groupId, callback) {
    toolUtil.getAndCacheHuanXinToken(function (err, token) {
        var args = {
            data: {},
            headers: {
                "Content-Type": "application/json",
                "Authorization": "Bearer " + token
            }
        };
        restClient.get("https://a1.easemob.com/66xiaoqu/" + huanxinEnv + "/chatgroups/" + groupId + "/users", args, function (data, response) {
            logger.info(data);
            if (response.statusCode == '200') {

                var nameList = new Array();
                for (var i = 0; i < data.data.length - 1; i++) {
                    nameList[i] = data.data[i].member;
                }

                Users.find({'huanxinUserName': {'$in': nameList}}, '_id nickName images', callback);
            } else {
                callback(null, null);
            }
        });
    });
};

/**
 * 搜索活动地点
 * @param keyword
 * @param callback
 */
exports.searchActivityVenueByKeywordService = function (keyword, callback) {
    restClient.get('http://api.map.baidu.com/place/v2/search?&query=' + keyword + '&region=上海&scope=2&output=json&ak=AvRqTglpaKICTZ5iwyn06KZj&radius=1000&page_size=20&page_num=0', function (data, response) {
        if (response.statusCode == 200) {
            data = JSON.parse(data);
            if (JSON.stringify(data.results).indexOf("location") > 0) {
                var result = new Array();
                for (var i = 0; i < data.results.length; i++) {
                    var v = {
                        "name": data.results[i].name,
                        "address": data.results[i].address
                    }
                    result[i] = v;
                }
                callback(null, result);
            } else {
                callback(null, null);
            }
        } else {
            var err = {
                "message": 'statusCode:' + response.statusCode
            };
            callback(err, null);
        }
    }).on('error', function (err) {
        logger.error('get Community List by keyword went wrong on the request' + err.message);
    });
};

exports.postTextMessageService = function (token, input, callback) {
    toolUtil.getUserByToken(token, function (err, user) {
        if (user == null || user.huanxinUserName == null) {
            var msg = {
                "message": noUserErrMessage
            };
            callback(msg, null);
        } else {
            var temp = new ActivityChats();
            temp.chatGroupId = input.chatGroupId;
            temp.from = user.huanxinUserName;
            temp.textMessage = input.textMessage;
            temp.nickName = user.nickName;
            if (user.images != null && user.images.length > 0) {
                temp.portrait = user.images[0].imageURL;
            }
            temp.save(callback);
        }
    });
};


exports.getActivityChatsService = function (groupId, callback) {
    ActivityChats.find({'chatGroupId': groupId}, '-_id from textMessage nickName portrait dateCreated').sort('dateCreated').exec(function (err, results) {
        if (results != null) {
            results.forEach(function (result) {
                result._doc.dateCreated = new Date(result.dateCreated).getTime();
            })
        }
        callback(err, results);
    });
};

//=================================新版===============================

/**
 * 创建邻里活动
 * @param token
 * @param input
 * @param callback
 */
exports.postNeighbourActivityService = function (token, input, callback) {
    toolUtil.getUserByToken(token, function (err, user) {
        if (err) {
            callback(err, null)
        } else {

            var activity;
            var tag;
            async.series([
                function (callbackInner) {

                    var desc = input.desc.replace(/[\r\n]{2,}/g, "\n").trim();
                    var temp = new neighbourActivity();
                    temp.title = input.title;
                    temp.desc = desc;
                    temp.images = input.images;
                    temp.activityType = input.activityType;
                    if (input.deadline != null) {
                        temp.deadline = moment(input.deadline).toDate();
                    } else {
                        temp.deadline = moment().add(1, 'month').toDate();
                    }
                    temp.createdBy = user._id;
                    temp.community = user.community._id;

                    try {                               //打标签

                        var str = input.title + '||' + input.desc;

                        restClient.get('http://' + RecommendHost + ':8002?data=' + str, function (data, response) {
                            if (response.statusCode == 200 && data != null && data != '') {
                                var sensitive = JSON.parse(data).sensitive;
                                tag = JSON.parse(data).tag;
                                if (sensitive != null) {
                                    temp.title = sensitive.split('||')[0]
                                    temp.desc = sensitive.split('||')[1];
                                }
                                Dic.find({'value': {'$in': tag}, 'category': '02'}, '_id', function (err, res) {
                                    if (res != null) {
                                        temp.tag = res;
                                        tag = res;
                                    }
                                    temp.save(function (err, result) {
                                        activity = result;
                                        callbackInner(err, result);
                                    });
                                });
                            } else {
                                temp.save(function (err, result) {
                                    activity = result;
                                    callbackInner(err, result);
                                })
                            }
                        }).on('error', function (err) {
                            logger.error('get activity tag around went wrong on the request' + err.message);
                            temp.save(function (err, result) {
                                activity = result;
                                callbackInner(err, result)
                            })
                        });
                    } catch (e) {
                        logger.error("postNeighbourActivityService--tag--" + e);
                        temp.save(function (err, result) {
                            activity = result;
                            callbackInner(err, result)
                        })
                    }
                },
                function (callbackInner) {              //统计
                    redisClient.hincrby('q:count:' + user.community._id, 'neighbourActivityQuestionCount', 1);
                    callbackInner(null, null);
                },
                function (callbackInner) {               //建立索引
                    var temp = new ugcIndex();
                    temp.ugcId = activity._id;
                    temp.category = 'neighbourActivity';
                    temp.community = activity.community;
                    temp.createdBy = activity.createdBy;
                    if (tag != null)
                        temp.tag = tag;
                    temp.save(callbackInner);


                    UserFollowups.find({'followUser': user._id}, 'user').populate('user', '_id community').exec(function (err, results) {
                        if (results != null && results.length > 0) {

                            var users = new Array();
                            results.forEach(function (result) {

                                if (result.user != null && user.community._id == result.user.community) {
                                    var temp = new SystemMessage();
                                    temp.toUser = result.user._id;
                                    temp.content.questionDesc = '';
                                    temp.content.replyDesc = '发布了活动：' + activity.title;
                                    temp.content.title = user.nickName;
                                    temp.content.contentId = activity._id;
                                    temp.content.contentType = 'myFollowupUser';
                                    temp.content.questionCreatedBy = user._id;
                                    temp.category = 'neighbourActivity';
                                    temp.fromUser = user._id;
                                    temp.save();

                                    users.push(result.user._id);
                                }
                            });

                            //个推
                            var content = {
                                type: 1,
                                flag: 1,
                                openType: 6,
                                contentId: activity._id,
                                createdBy: user._id,
                                desc: user.nickName + '发布了活动：' + activity.title
                            };
                            var pushData = {
                                uList: users,
                                content: content,
                                type: 'user'
                            };
                            toolUtil.putMessageGetuiPushMQ(pushData);
                        }
                    });
                }
            ], callback)
        }
    })
};

/**
 * 参与活动
 * @param token
 * @param input
 * @param callback
 */
exports.joinInNeighbourActivityService = function (token, input, callback) {
    toolUtil.getUserByToken(token, function (err, user) {
        if (err) {
            callback(err, null);
        } else {
            var partakeNum;

            async.series([
                function (callbackInner) {
                    neighbourActivity.findOne({
                        _id: input.activityId,
                        status: true,
                        isValid: true
                    }, function (err, result) {
                        if (result == null) {
                            var msg = {
                                message: '活动已关闭'
                            };
                            callbackInner(msg, null);
                        } else {
                            partakeNum = result.partake.length;
                            callbackInner();
                        }
                    })
                },
                function (callbackInner) {
                    neighbourActivity.findOne({
                        _id: input.activityId,
                        isValid: true,
                        'partake.user': user._id
                    }, 'partake', function (err, result) {
                        if (result == null) {
                            var temp = {
                                user: user._id,
                                number: input.number
                            };
                            neighbourActivity.update({_id: input.activityId}, {
                                $push: {partake: temp}, partakeNum: partakeNum + 1
                            }, callbackInner)
                        } else {
                            var number = input.number;
                            result.partake.forEach(function (par) {
                                if (par.user == user._id) {
                                    number += par.number;
                                }
                            });

                            neighbourActivity.update({
                                _id: input.activityId,
                                'partake.user': user._id
                            }, {'partake.$.number': number, 'partake.$.time': new Date()}).exec(callbackInner);
                        }
                    });
                },
                function (callbackInner) {
                    neighbourActivity.update({_id: input.activityId}, {dateLastModified: new Date()}, callbackInner)
                },
                function (callbackInner) {
                    neighbourActivity.findOne({_id: input.activityId}, '_id title partake createdBy', function (err, result) {

                        var number = 0;
                        result.partake.forEach(function (par) {
                            number += par.number;
                        });

                        callbackInner(null, number);

                        if (result.createdBy != user._id) {
                            var temp = new SystemMessage();
                            temp.toUser = result.createdBy;
                            temp.content.questionDesc = '';
                            temp.content.replyDesc = '参加了您的活动' + '【' + result.title + '】'
                            temp.content.title = user.nickName;
                            temp.content.contentId = result._id;
                            temp.content.contentType = 'partake';
                            temp.content.questionCreatedBy = result.createdBy;
                            temp.category = 'partake';
                            temp.fromUser = user._id;
                            temp.save();

                            //个推
                            var content = {
                                type: 1,
                                flag: 1,
                                openType: 5,
                                contentId: result._id,
                                createdBy: result.createdBy,
                                desc: user.nickName + '参加了您的活动' + '【' + result.title + '】'
                            };
                            var pushData = {
                                uList: [result.createdBy],
                                content: content,
                                type: 'user'
                            };
                            toolUtil.putMessageGetuiPushMQ(pushData);
                        }
                    });
                }
            ], callback)
        }
    });
};

exports.joinInActivityNewService = function (token, input, callback) {
    toolUtil.getUserByToken(token, function (err, user) {
        if (err) {
            callback(err, null)
        } else {
            var partakeNum;
            var pushFlag;

            async.series([
                function (callbackInner) {
                    neighbourActivity.findOne({
                        _id: input.activityId,
                        status: true,
                        isValid: true
                    }, function (err, result) {
                        if (result == null) {
                            callbackInner(ErrorMessage.ACTIVITY_CLOSE, null);
                        } else {
                            if (result.deadline != null && result.deadline.getTime() < new Date().getTime()) {
                                callbackInner(ErrorMessage.ACTIVITY_CLOSE, null);
                            } else {
                                partakeNum = result.partakeNum;
                                callbackInner();
                            }
                        }
                    })
                },
                function (callbackInner) {
                    neighbourActivity.findOne({
                        _id: input.activityId,
                        isValid: true,
                        'partake.user': user._id
                    }, 'partake', function (err, result) {
                        if (result == null) {
                            pushFlag = true;
                            var temp = {
                                user: user._id,
                                number: input.number,
                                partakeType: 1,
                                phone: input.phone,
                                note: input.note
                            };
                            neighbourActivity.update({_id: input.activityId}, {
                                $push: {partake: temp}, partakeNum: partakeNum + 1
                            }, callbackInner)
                        } else {
                            pushFlag = false;
                            var update = {
                                'partake.$.number': input.number,
                                'partake.$.phone': input.phone,
                                'partake.$.time': new Date()
                            };
                            if (input.note != null) {
                                update['partake.$.note'] = input.note;
                            }
                            neighbourActivity.update({
                                _id: input.activityId,
                                'partake.user': user._id
                            }, update).exec(callbackInner);
                        }
                    });
                },
                function (callbackInner) {
                    neighbourActivity.update({_id: input.activityId}, {dateLastModified: new Date()}, callbackInner)
                },
                function (callbackInner) {
                    neighbourActivity.findOne({_id: input.activityId}, '_id title partake createdBy')
                        .populate('partake.user', '_id nickName images userType authenticationStatus')
                        .exec(function (err, result) {
                            var uList = [];
                            result.partake.forEach(function (par) {
                                if (par.partakeType == 2) {
                                    par._doc.user = {
                                        nickName: par.name,
                                        images: [{imageURL: wechatImage}]
                                    }
                                }

                                if (par._doc.user != null && uList.length < 9) {
                                    uList.push(par.user)
                                }
                            });

                            var data = {
                                partakeNum: result.partake.length + '',
                                uList: uList
                            };

                            callbackInner(null, data);

                            if (result.createdBy != user._id && pushFlag) {
                                var temp = new SystemMessage();
                                temp.toUser = result.createdBy;
                                temp.content.questionDesc = '';
                                temp.content.replyDesc = '参加了您的活动' + '【' + result.title + '】'
                                temp.content.title = user.nickName;
                                temp.content.contentId = result._id;
                                temp.content.contentType = 'partake';
                                temp.content.questionCreatedBy = result.createdBy;
                                temp.category = 'partake';
                                temp.fromUser = user._id;
                                temp.save();

                                //个推
                                var content = {
                                    type: 1,
                                    flag: 1,
                                    openType: 5,
                                    contentId: result._id,
                                    createdBy: result.createdBy,
                                    desc: user.nickName + '参加了您的活动' + '【' + result.title + '】'
                                };
                                var pushData = {
                                    uList: [result.createdBy],
                                    content: content,
                                    type: 'user'
                                };
                                toolUtil.putMessageGetuiPushMQ(pushData);
                            }
                        });
                },
                function (callbackInner) {
                    PartakeInfo.remove({user: user._id}, function (err, result) {
                        var temp = new PartakeInfo();
                        temp.activity = input.activityId;
                        temp.phone = input.phone;
                        temp.user = user._id;
                        temp.save(callbackInner);
                    });
                }
            ], callback)
        }
    })
};

exports.exitNeighbourActivityService = function (token, activityId, callback) {
    toolUtil.getUserByToken(token, function (err, user) {
        if (err) {
            callback(err, null);
        } else {
            neighbourActivity.findOne({_id: activityId}, 'status partake', function (err, result) {

                if (!result.status) {
                    var msg = {
                        message: '活动已结束，无法退出'
                    };
                    callback(msg, null)
                } else {

                    var partake = result.partake.length;
                    if (partake > 0) {
                        partake = partake - 1;
                    }

                    neighbourActivity.update({_id: activityId}, {
                        $pull: {partake: {user: user._id}},
                        partakeNum: partake
                    }, function (err, data) {
                        if (err) {
                            callback(err, null)
                        } else {
                            neighbourActivity.findOne({_id: activityId}, '_id title status createdBy partake', function (err, result) {
                                var number = 0;
                                result.partake.forEach(function (par) {
                                    number += par.number;
                                });
                                callback(err, number);

                                if (result.createdBy != user._id) {
                                    var temp = new SystemMessage();
                                    temp.toUser = result.createdBy;
                                    temp.content.questionDesc = '';
                                    temp.content.replyDesc = '退出了您的活动' + '【' + result.title + '】';
                                    temp.content.title = user.nickName;
                                    temp.content.contentId = result._id;
                                    temp.content.contentType = 'partake';
                                    temp.content.questionCreatedBy = result.createdBy;
                                    temp.category = 'partake';
                                    temp.fromUser = user._id;
                                    temp.save();

                                    //个推
                                    var content = {
                                        type: 1,
                                        flag: 1,
                                        openType: 5,
                                        contentId: result._id,
                                        createdBy: result.createdBy,
                                        desc: user.nickName + '退出了您的活动' + '【' + result.title + '】'
                                    };
                                    var pushData = {
                                        uList: [result.createdBy],
                                        content: content,
                                        type: 'user'
                                    };
                                    toolUtil.putMessageGetuiPushMQ(pushData);
                                }
                            });
                        }
                    });
                }

            });
        }
    });
};
exports.getDetailOfActivityService = function (token, activityId, callback) {
    toolUtil.getUserByToken(token, function (err, user) {
        if (err) {
            callback(err, null)
        } else {
            neighbourActivity.findOne({
                _id: activityId,
                isValid: true
            }, '_id level displayOrder title desc community category activityType browserCount status tag images.imageURL images._id dateCreated createdBy partake partakeNum deadline lastReply praiseCount')
                .populate('tag', 'category value _id').populate('community', '_id communityName')
                .populate('createdBy', '_id nickName images userType authenticationStatus roomUnit showUnit')
                .populate('partake.user', '_id nickName images userType authenticationStatus')
                .exec(function (err, result) {

                    PartakeInfo.findOne({user: user._id}, function (err, info) {

                        var partakeInfo = {};

                        if (user.mobilePhone != null) {
                            partakeInfo.phone = user.mobilePhone;
                        } else if (info != null) {
                            partakeInfo.phone = info.phone;
                        }

                        if (result != null) {
                            var number = 0;
                            var uList = [];
                            result._doc['isJoined'] = false;
                            result.partake.forEach(function (par) {
                                number += par.number;
                                if (par.user != null && par.user._id == user._id) {
                                    result._doc['isJoined'] = true;
                                    partakeInfo = {
                                        number: par.number,
                                        phone: par.phone
                                    };
                                    if (par.note != null) {
                                        partakeInfo.note = par.note;
                                    }
                                }
                                if (par.partakeType == 2) {
                                    par._doc.user = {
                                        nickName: par.name,
                                        images: [{imageURL: wechatImage}]
                                    }
                                }

                                if (par._doc.user != null && uList.length < 9) {
                                    uList.push(par.user)
                                }

                            });

                            result._doc.uList = uList;
                            result._doc.partakeInfo = partakeInfo;
                            result.browserCount = result.browserCount + 1;

                            result._doc.number = number;
                            result._doc.partakeNum = result.partake.length + '';
                            result._doc.partake = undefined;
                            result._doc['browserCountStr'] = toolUtil.transformNumber(result.browserCount);
                            result._doc['activityStatus'] = result.status;

                            if (result.createdBy.showUnit != null && !result.createdBy.showUnit) {
                                result.createdBy.roomUnit = undefined;
                            }
                            result.createdBy.showUnit = undefined;

                            result._doc['isTop'] = result.displayOrder == 3 ? true : false;
                            result._doc['isPrime'] = result.level == 1;

                            ugcIndex.findOne({ugcId: activityId}, function (err, index) {
                                result._doc['isTopAll'] = index.displayOrder ? true : false;
                                callback(err, result);
                            });

                            //callback(err, result);

                            neighbourActivity.update({_id: activityId}, {browserCount: result.browserCount}, function (err, result) {
                            })

                        } else {
                            var msg = {
                                message: '无此活动或已被删除'
                            };
                            callback(msg, null);
                        }
                    })
                })
        }
    })
};

/**
 * 获取回复活动详情
 * @param token
 * @param activityId
 * @param page
 * @param callback
 */
exports.getDetailReplyOfActivityService = function (token, activityId, page, vcode, callback) {
    toolUtil.getUserByToken(token, function (err, user) {
        if (err) {
            callback(err, null)
        } else {
            var data = [];
            neighbourActivity.findOne({
                _id: activityId,
                'isValid': true
            }, 'createdBy replies.replyStatus replies._id replies.replyDesc replies.images.imageURL replies.images._id replies.replyType  replies.dateReplied replies.repliedBy replies.replyTo')
                .populate('createdBy', '_id nickName images userType authenticationStatus')
                .populate('replies.repliedBy', '_id nickName images userType authenticationStatus showUnit roomUnit')
                .populate('replies.replyTo', '_id nickName images')
                .exec(function (err, result) {
                    if (result == null || result.replies == null) {
                        callback(null, data);
                    } else {
                        result.replies.sort(function (a, b) {
                            return a.dateReplied - b.dateReplied
                        });

                        async.each(result.replies, function (reply, callback1) {

                            if (reply.repliedBy.showUnit != null && !reply.repliedBy.showUnit) {
                                reply.repliedBy.roomUnit = undefined;
                            }
                            reply.repliedBy.showUnit = undefined;

                            if (reply.replyTo == null) {
                                reply.replyTo = undefined;
                            }
                            reply.displayOrder = undefined;

                            QuestionReplyThank.findOne({
                                'reply': reply._doc._id,
                                'user': result.createdBy._id
                            }, function (err, result) {
                                if (result == null) {
                                    reply._doc['isThank'] = 'No'
                                } else {
                                    reply._doc['isThank'] = 'Yes'
                                }

                                QuestionReplyPraise.find({'reply': reply._id}, '', function (err, resPra) {
                                    if (resPra == null) {
                                        reply._doc['praiseCount'] = 0
                                    } else {
                                        reply._doc['praiseCount'] = resPra.length;
                                        reply._doc['isPraise'] = 'No';
                                        resPra.forEach(function (res) {
                                            if (res.user == user._id) {
                                                reply._doc['isPraise'] = 'Yes'
                                            }
                                        });
                                    }
                                    if (reply.replyDesc.indexOf(atFlag) != -1) {

                                        replyAt.findOne({replyId: reply._id + ''}, function (err, at) {
                                            if (at != null && at.uList != null) {
                                                if (vcode < 1500) {
                                                    at.uList.forEach(function (temp, i) {
                                                        reply.replyDesc = reply.replyDesc.replace(new RegExp("@\\{" + i + "\\}"), '@' + temp.nickName + ' ')
                                                    });
                                                } else {
                                                    reply._doc['uList'] = at.uList;
                                                }
                                            }
                                            callback1(err, null);
                                        }).populate('uList', '_id nickName');
                                    } else {
                                        callback1()
                                    }
                                });
                            });
                        }, function (err) {
                            if (err) {
                                callback(err, null);
                            } else {
                                page = Number(page);
                                var replies = result.replies.slice(page * listPageSize, (page + 1) * listPageSize);
                                var temp = {
                                    replyCount: result.replies.length,
                                    replyCountStr: toolUtil.transformNumber(result.replies.length),
                                    replies: replies
                                };
                                callback(null, temp);
                            }
                        });
                    }
                });
        }
    })
};

/**
 * 获取参与人列表
 * @param token
 * @param activityId
 * @param callback
 * @param page
 */
exports.getActivityPartakeListService = function (token, activityId, page, callback) {
    toolUtil.getUserByToken(token, function (err, user) {
        if (err) {
            callback(err, null);
        } else {
            neighbourActivity.findOne({_id: activityId, isValid: true}, 'title partake')
                .populate('partake.user', '_id nickName authenticationStatus images userType roomUnit showUnit mobilePhone')
                .exec(function (err, result) {
                    var data = {};
                    var users = [];
                    if (result != null) {
                        data.users = result.partake.length;
                        var number = 0;

                        result.partake.forEach(function (par) {
                            par._id = undefined;

                            if (par.user != null) {
                                number += par.number;
                                users.push(par);
                            }
                        });
                        data.total = number;
                        data.title = result.title;

                        users.sort(function (a, b) {
                            return b.time - a.time;
                        });

                        page = Number(page);
                        var temp = users.slice(page * listPageSize, (page + 1) * listPageSize);

                        data.partake = temp;
                    }
                    callback(err, data);
                })
        }
    })
};

//1.5.0
exports.getActivityPartakeListNewService = function (token, activityId, page, callback) {
    neighbourActivity.findOne({_id: activityId}, 'activityType partake')
        .populate('partake.user', '_id nickName authenticationStatus images userType roomUnit showUnit')
        .exec(function (err, result) {
            var number = 0;
            result.partake.forEach(function (par) {
                number += par.number;
                par.partakeStatus = undefined;
                if (par.partakeType == 2) {
                    par._doc.user = {
                        nickName: par.name,
                        images: [{imageURL: wechatImage}]
                    }
                }

                if (par.user != null && !par.user.showUnit) {
                    par.user.roomUnit = undefined;
                }
            });

            result.partake.sort(function (a, b) {
                return b.time - a.time;
            });

            page = Number(page);
            var temp = result.partake.slice(page * listPageSize, (page + 1) * listPageSize);

            temp.forEach(function (par) {
                par._doc.time = moment(par.time).format('YYYY-MM-DD')
            });
            var data = {
                totalNum: number,
                activityType: result.activityType,
                partake: temp
            };
            callback(null, data);
        });
};

exports.searchPartakeService = function (keyword, activityId, callback) {
    logger.info(keyword);
    neighbourActivity.findOne({_id: activityId}, 'activityType partake')
        .populate('partake.user', '_id nickName authenticationStatus images userType roomUnit showUnit')
        .exec(function (err, result) {
            var data = [];
            result.partake.forEach(function (par) {
                par.partakeStatus = undefined;
                if (par.partakeType == 2) {
                    par._doc.user = {
                        nickName: par.name,
                        images: [{imageURL: wechatImage}]
                    }
                }

                if (par._doc.user != null && par._doc.user.nickName != null && par._doc.user.nickName.indexOf(keyword) != -1) {
                    data.push(par)
                }
            });

            data.forEach(function (par) {
                par._doc.time = moment(par.time).format('YYYY-MM-DD HH:mm')
            });

            callback(null, data);
        });
};

exports.setPartakeManagerStatusService = function (input, callback) {

    logger.info(input);

    if (input.type == 1) {
        neighbourActivity.update({
            _id: input.activityId,
            'partake._id': input.partakeId
        }, {'partake.$.sendStatus': true}).exec(callback);
    } else if (input.type == 2) {
        neighbourActivity.update({
            _id: input.activityId,
            'partake._id': input.partakeId
        }, {'partake.$.payStatus': true}).exec(callback);
    } else {
        callback();
    }
};

/**
 * 评论活动
 * @param token
 * @param activityId
 * @param input
 * @param callback
 */
exports.postActivityReplyService = function (token, activityId, input, callback) {
    toolUtil.getUserByToken(token, function (err, user) {
        if (err) {
            callback(err, null)
        } else {
            if (user._id == input.replyTo) {
                input.replyTo = null;
            }
            var activity;
            async.series([
                function (callbackInner) {
                    var desc = input.replyDesc.replace(/[\r\n]{2,}/g, "\n").trim();
                    var rep = {
                        'replyDesc': desc,
                        'replyTo': input.replyTo,
                        'repliedBy': user._id,
                        'images': input.images
                    };
                    neighbourActivity.update({_id: activityId}, {
                        $push: {'replies': rep},
                        lastReply: new Date(),
                        dateLastModified: new Date()
                    }).exec(callbackInner);
                },
                function (callbackInner) {
                    redisClient.hincrby('q:count:' + user.community._id, 'neighbourActivityReplyCount', 1);
                    callbackInner();
                },
                function (callbackInner) {
                    ugcIndex.update({ugcId: activityId}, {lastReply: new Date()}, callbackInner);
                },
                function (callbackInner) {
                    neighbourActivity.findOne({_id: activityId}, function (err, result) {
                        activity = result;
                        activity._doc['huanxinName'] = user.huanxinUserName;
                        callbackInner(err, result);

                        ugcReply.findOne({ugcId: result._id, repliedBy: user._id}, function (err, data) {
                            if (data == null) {
                                var temp = new ugcReply();
                                temp.ugcId = result._id;
                                temp.ugcReply = [{
                                    replyId: result.replies[result.replies.length - 1]._id
                                }];
                                temp.category = result.category;
                                temp.community = result.community;
                                temp.createdBy = result.createdBy;
                                temp.repliedBy = user._id;
                                temp.save();
                            } else {
                                var temp = {
                                    replyId: result.replies[result.replies.length - 1]._id
                                };
                                data.ugcReply.push(temp);
                                data.lastReply = new Date();
                                data.save()
                            }
                        })
                    });
                },
                function (callbackInner) {
                    //if (input.replyTo != null) {
                    //    var temp = new SystemMessage();
                    //    temp.toUser = input.replyTo;
                    //    temp.content.questionDesc = activity.desc;
                    //    temp.content.replyDesc = input.replyDesc;
                    //    temp.content.replyId = activity.replies[activity.replies.length - 1]._id;
                    //    temp.content.title = user.nickName;
                    //    temp.content.contentId = activity._id;
                    //    temp.content.contentType = 'myReply';
                    //    temp.content.questionCreatedBy = activity.createdBy;
                    //    temp.category = 'neighbourActivity';
                    //    temp.fromUser = user._id;
                    //    temp.save();
                    //
                    //    //个推
                    //    var content = {
                    //        type: 1,
                    //        flag: 1,
                    //        openType: 6,
                    //        contentId: activity._id,
                    //        createdBy: activity.createdBy,
                    //        desc: user.nickName + '回复了你的回复'
                    //    };
                    //    var pushData = {
                    //        uList: [input.replyTo],
                    //        content: content,
                    //        type: 'user'
                    //    };
                    //    toolUtil.putMessageGetuiPushMQ(pushData);
                    //}
                    callbackInner();
                },
                function (callbackInner) {
                    //if (input.replyTo == null && user._id != activity.createdBy) {
                    //
                    //    var temp = new SystemMessage();
                    //    temp.toUser = activity.createdBy;
                    //    temp.content.questionDesc = activity.desc;
                    //    temp.content.replyDesc = input.replyDesc;
                    //    temp.content.replyId = activity.replies[activity.replies.length - 1]._id;
                    //    temp.content.title = user.nickName;
                    //    temp.content.contentId = activity._id;
                    //    temp.content.contentType = 'myQuestion';
                    //    temp.content.questionCreatedBy = activity.createdBy;
                    //    temp.category = 'neighbourActivity';
                    //    temp.fromUser = user._id;
                    //    temp.save();
                    //
                    //    //个推
                    //    var content = {
                    //        type: 1,
                    //        openType: 6,
                    //        flag: 1,
                    //        contentId: activity._id,
                    //        createdBy: activity.createdBy,
                    //        desc: user.nickName + '回复了你的发布'
                    //    };
                    //    var pushData = {
                    //        uList: [activity.createdBy],
                    //        content: content,
                    //        type: 'user'
                    //    };
                    //    toolUtil.putMessageGetuiPushMQ(pushData);
                    //}
                    callbackInner();
                }
            ], callback);
        }
    })
};

exports.thankActivityReplyService = function (activityId, replyId, replyBy, token, callback) {
    toolUtil.getUserByToken(token, function (err, user) {
        if (err) {
            callback(err, null)
        } else {
            QuestionReplyThank.findOne({'user': user._id, 'reply': replyId}, function (err, result) {
                if (result != null) {
                    var msg = {
                        "message": "你已经感谢过了"
                    };
                    callback(msg, null);
                } else {
                    neighbourActivity.findOne({
                        _id: activityId,
                        'isValid': true
                    }).populate('createdBy', '_id nickName').exec(function (err, result) {
                        var tempT = new QuestionReplyThank();
                        tempT.user = user._id;
                        tempT.reply = replyId;
                        tempT.replyBy = replyBy;
                        tempT.save();

                        var nickName = user.nickName;
                        if (nickName == undefined) {
                            nickName = '有人'
                        }

                        var content = {
                            type: 1,
                            openType: 5,
                            flag: 1,
                            contentId: activityId,
                            createdBy: result.createdBy._id,
                            desc: nickName + '感谢了你'
                        };
                        var pushData = {
                            uList: [replyBy],
                            content: content,
                            type: 'user'
                        };
                        toolUtil.putMessageGetuiPushMQ(pushData);


                        callback(err, null);


                        var temp = new SystemMessage();
                        temp.toUser = replyBy;
                        temp.content.questionDesc = result.desc;
                        temp.content.replyDesc = '你的回复很好，非常感谢你对我的帮助';
                        temp.content.title = nickName;
                        temp.content.contentId = result._id;
                        temp.content.contentType = 'myThank';
                        temp.content.questionCreatedBy = result.createdBy._id;
                        temp.category = 'neighbourActivity';
                        temp.fromUser = user._id;
                        temp.save(function (err, re) {
                            if (err) {
                                logger.error('thankReply-----' + err);
                            }
                        });
                    });
                }
            });
        }
    })
};

/**
 * 删除活动回复
 */
exports.deleteActivityReplyService = function (token, activityId, replyId, callback) {
    toolUtil.getUserByToken(token, function (err, user) {
        if (err) {
            callback(err, null);
        } else {
            async.series([
                function (callbackInner) {
                    neighbourActivity.update({_id: activityId}, {
                        $pull: {
                            replies: {
                                _id: replyId,
                                repliedBy: user._id
                            }
                        }
                    }).exec(callbackInner);
                },
                function (callbackInner) {
                    ugcReply.update({repliedBy: user._id, ugcId: activityId}, {
                        $pull: {
                            ugcReply: {
                                replyId: replyId
                            }
                        }
                    }, callbackInner)
                },
                function (callbackInner) {
                    neighbourActivity.findOne({_id: activityId}, 'community', function (err, result) {
                        if (result.category != null)
                            redisClient.hincrby('q:count:' + result.community, 'neighbourActivityReplyCount', -1);
                        callbackInner();
                    })
                }
            ], callback)
        }
    })
};

/**
 * 删除活动
 * @param token
 * @param activityId
 * @param callback
 */
exports.deleteActivityService = function (token, activityId, callback) {
    neighbourActivity.findOne({_id: activityId}, function (err, result) {
        if (result != null && result.partake.length > 0) {
            var msg = {
                message: '您的活动已经有人参加，不能删除活动'
            };
            callback(msg, null);
        } else {
            async.series([
                function (callbackInner) {
                    neighbourActivity.update({_id: activityId}, {isValid: false}, callbackInner)
                },
                function (callbackInner) {
                    neighbourActivity.findOne({_id: activityId}, function (err, result) {
                        if (result != null) {
                            var replyC = result.replies.length;
                            redisClient.hincrby('q:count:' + result.community, 'neighbourActivityQuestionCount', -1);
                            redisClient.hincrby('q:count:' + result.community, 'neighbourActivityReplyCount', -replyC);
                        }
                        callbackInner();
                    });
                },
                function (callbackInner) {
                    ugcIndex.remove({ugcId: activityId}, callbackInner)
                },
                function (callbackInner) {
                    ugcReply.remove({ugcId: activityId}, callbackInner);
                },
                function (callbackInner) {
                    SystemMessage.remove({'content.contentId': activityId}, callbackInner);
                }
            ], callback)
        }
    })
};


exports.closeActivityService = function (token, activityId, callback) {
    toolUtil.getUserByToken(token, function (err, user) {
        if (err) {
            callback(err, null)
        } else {
            neighbourActivity.findOne({_id: activityId}, 'createdBy', function (err, result) {
                if (result.createdBy != user._id) {
                    var msg = {
                        "message": '不是自己的活动'
                    };
                    callback(msg, null)

                } else {
                    neighbourActivity.update({_id: activityId}, {
                        displayOrder: 1,
                        status: false,
                        deadline: new Date(),
                        dateLastModified: new Date()
                    }, callback);
                }
            })
        }
    })
};

exports.setPartakeStatusService = function (input, callback) {
    neighbourActivity.update({
        _id: input.activityId,
        'partake.user': input.userId
    }, {'partake.$.partakeStatus': input.status}).exec(callback);
};
/**
 * 获取活动列表service
 * @param token
 * @param date
 * @param callback
 */
exports.getActivityListService = function (token, ts, level, noTag, callback) {
    toolUtil.getUserByToken(token, function (err, user) {
        if (err) {
            callback(err, null)
        } else {

            var date = ts == '0' ? new Date() : new Date(Number(ts));

            var index = Number(ts) * listPageSize;

            var opt = {
                community: user.community._id,
                isValid: true
                //dateCreated: {$lt: date}
            };

            if (level != null) {
                opt.level = 1;
            }

            if (noTag != null) {
                opt.tag = {$size: 0};
            }

            //if (ts != '0') {
            //    opt.displayOrder = null;
            //}

            neighbourActivity.find(opt, '_id title desc category tag images.imageURL images._id level deadline partakeNum replies dateCreated createdBy partake lastReply displayOrder browserCount status activityType')
                .skip(index).limit(listPageSize)
                .populate('tag', 'category value _id')
                .populate('createdBy', '_id nickName images userType authenticationStatus roomUnit showUnit')
                .populate('partake.user', '_id nickName images userType authenticationStatus')
                .sort({
                    displayOrder: -1,
                    dateCreated: -1
                })
                .exec(function (err, result) {
                    var data = [];
                    if (result != null) {
                        result.forEach(function (activity) {
                            var uList = [];
                            var number = 0;
                            activity.partake.forEach(function (par) {
                                if (par.user != null)
                                    number += par.number;

                                if (par.partakeType == 2) {
                                    par._doc.user = {
                                        nickName: par.name,
                                        images: [{imageURL: wechatImage}]
                                    }
                                }

                                if (par._doc.user != null && uList.length < 9) {
                                    uList.push(par.user)
                                }
                            });
                            activity._doc['isPrime'] = activity.level == 1;
                            activity._doc.uList = uList;
                            activity._doc.number = number;
                            activity._doc.partakeNum = activity.partake.length + '';
                            activity._doc.partake = undefined;
                            activity._doc['numberOfReplies'] = activity.replies.length;
                            activity._doc['replyCountStr'] = toolUtil.transformNumber(activity.replies.length);
                            activity._doc['browserCountStr'] = toolUtil.transformNumber(activity._doc.browserCount);
                            activity.replies = undefined;

                            if (activity.createdBy.showUnit != null && !activity.createdBy.showUnit) {
                                activity.createdBy.roomUnit = undefined;
                            }
                            activity.createdBy.showUnit = undefined;

                            activity._doc['activityStatus'] = activity.status;
                            activity._doc['isTop'] = activity.displayOrder == 3;
                            data.push(activity);
                        })
                    }
                    callback(err, data);
                })
        }
    })
};

/**
 * 举报活动
 */
exports.reportActivityService = function (token, activityId, callback) {
    toolUtil.getUserByToken(token, function (err, user) {
        if (err) {
            callback(err, null);
        } else {
            QuestionReport.findOne({
                'activity': activityId,
                'reportUser': user._id
            }, '', function (err, result) {
                if (err) {
                    callback(err, result);
                } else {
                    if (result == null) {
                        var temp = new QuestionReport();
                        temp.activity = activityId;
                        temp.reportUser = user._id;
                        temp.save(callback);
                    } else {
                        var msg = {
                            "message": "已经举报过了"
                        };
                        callback(msg, null);
                    }
                }
            })
        }
    });
};


exports.getMyInvolvedActivityService = function (token, ts, callback) {
    toolUtil.getUserByToken(token, function (err, user) {
        if (err) {
            callback(ErrorMessage.LOGON_EXPIRED)
        } else {
            var date = ts == '0' ? new Date() : new Date(Number(ts));

            var index = Number(ts) * listPageSize;

            neighbourActivity.find({
                createdBy: {$ne: user._id},
                community: user.community._id,
                isValid: true,
                'partake.user': user._id,
                dateCreated: {$lt: date}
            }, '_id title desc images category createdBy deadline partake partakeNum dateCreated browserCount replies activityType status')
                .sort({
                    dateCreated: -1
                }).limit(listPageSize)
                .populate('createdBy', '_id nickName images userType authenticationStatus')
                .populate('partake.user', '_id nickName images userType authenticationStatus')
                .exec(function (err, result) {
                    var data = [];
                    if (result != null) {
                        result.forEach(function (activity) {
                            var uList = [];
                            activity.partake.forEach(function (par) {
                                if (par.partakeType == 2) {
                                    par._doc.user = {
                                        nickName: par.name,
                                        images: [{imageURL: wechatImage}]
                                    }
                                }

                                if (par._doc.user != null && uList.length < 9) {
                                    uList.push(par.user)
                                }
                                if (par._doc.user._id == user._id) {
                                    activity._doc['myNote'] = par.note;
                                    activity._doc['myNumber'] = par.number;
                                }
                            });
                            activity._doc['numberOfReplies'] = activity.replies.length;
                            activity._doc['replyCountStr'] = toolUtil.transformNumber(activity.replies.length);
                            activity._doc['browserCountStr'] = toolUtil.transformNumber(activity._doc.browserCount);
                            activity.replies = undefined;
                            activity._doc.uList = uList;
                            activity._doc.partakeNum = activity.partake.length + '';
                            activity._doc['activityStatus'] = activity.status;
                            activity._doc.partake = undefined;
                            data.push(activity);
                        })
                    }
                    callback(null, data);
                })
        }
    })
};

exports.getMyReleasedActivityService = function (token, ts, callback) {
    toolUtil.getUserByToken(token, function (err, user) {
        if (err) {
            callback(ErrorMessage.LOGON_EXPIRED)
        } else {

            var date = ts == '0' ? new Date() : new Date(Number(ts));

            var index = Number(ts) * listPageSize;

            neighbourActivity.find({
                createdBy: user._id,
                community: user.community._id,
                isValid: true,
                dateCreated: {$lt: date}
            }, '_id title desc images category createdBy deadline partake partakeNum dateCreated browserCount replies activityType status')
                .sort({
                    dateCreated: -1
                }).limit(listPageSize)
                .populate('createdBy', '_id nickName images userType authenticationStatus')
                .populate('partake.user', '_id nickName images userType authenticationStatus')
                .exec(function (err, result) {
                    var data = [];
                    if (result != null) {

                        async.eachSeries(result, function (activity, callbackInner) {
                            redisClient.get('activityid:' + activity._id + ':pushcount', function (err, pushCount) {
                                var uList = [];
                                activity.partake.forEach(function (par) {

                                    if (par.partakeType == 2) {
                                        par._doc.user = {
                                            nickName: par.name,
                                            images: [{imageURL: wechatImage}]
                                        }
                                    }

                                    if (par.user != null && uList.length < 9) {
                                        uList.push(par.user)
                                    }
                                });
                                activity._doc['pushCount'] = pushCount ? Number(pushCount) : 0;
                                activity._doc['totalPushCount'] = activityTotalPush;
                                activity._doc['numberOfReplies'] = activity.replies.length;
                                activity._doc['replyCountStr'] = toolUtil.transformNumber(activity.replies.length);
                                activity._doc['browserCountStr'] = toolUtil.transformNumber(activity._doc.browserCount);
                                activity.replies = undefined;
                                activity._doc.uList = uList;
                                activity._doc.partakeNum = activity.partake.length + '';
                                activity._doc.partake = undefined;
                                activity._doc['activityStatus'] = activity.status;
                                data.push(activity);
                                callbackInner()
                            });
                        }, function (err) {
                            callback(null, data);
                        });
                    } else {
                        callback(null, data);
                    }
                })
        }
    })
};
